const HOST = require('../../config.js').host

let app = getApp()

Page({
    data: {
        bannerHeight: '320',
        // mainImageHeight: '',
        // galleryImageHeight: '',
        bannerImages: [],
        current:0,
        activeIndex: 0,
        sliderOffset: 0,
        sliderLeft: 0,
        gallery: [{}, {}, {}, {}],
        _gallery: []
    },

    /**
     * 分享
     */
    onShareAppMessage () {
        return {
            title: '西湖礼物',
            path: '/pages/home/home'
        }
    },

  bindchange (e)
  {
    this.setData({
      current:e.detail.current
    })
  },


  bannerTap (){
    let current = this.data.current; //获取当前 banner 下标
    let obj = this.data.bannerImages[current]; //获取当前 banner 的 bannerId
    // console.log(obj);

   let objStr = JSON.stringify(obj)
  //  console.log(objStr)
    // if (bannerId == "8a9d450a5c8354bc015c9f4f320c0007")
    // {
      wx.navigateTo({
        url: `../bannerProList/bannerProList?obj=` + objStr,
      })

    // }
    // if (bannerId == "8a9d450a5c8354bc015c9f4f46540008") {
      // wx.navigateTo({
      //   url: `../graduate/graduate?bannerId=${bannerId}`
      // })
    // }
  },


    onLoadBannerImage (e) {
        this.setData({
            bannerHeight: e.detail.height
        })
    },

    tabClick: function (e) {
        let id = parseInt(e.currentTarget.id)
        let idx = e.currentTarget.dataset.idx
        let curTarget = e.currentTarget

        this.setData({
            'sliderOffset': curTarget.offsetLeft,
            // sliderLeft: this.data.padLeft,
            'activeIndex': idx
        });

        this.setGallery(idx)
    },

    /**
     * 查看商品详情
     */
    showDetail (e) {
        wx.navigateTo({
            url: `../detail/detail?id=${e.currentTarget.dataset.id}`
        })
    },

    /** 网络请求 **/
    getBanners () {
        let self = this
        wx.request({
            url: HOST + 'v1/banner/getList',
            method: 'GET',
            success (res) {
                if (res.data.sysCode === 1) {
                  console.log(res.length);
                    self.setData({
                        bannerImages: res.data.data
                    })
                }
            }
        })
    },

    /**
     * 获取全部商品数据
     */
    getGallerys () {
        // 数量需要人工修改
        for (let i = 0; i < 4; i++) {
            this.getGallery(i + 1, i);
        }
    },

    /**
     * 获取栏商品数据
     */
    getGallery (category, idx) {
        wx.request({
            url: HOST + 'v1/product/getListByType/' + category,
            method: 'GET', 
            success: function(res){
                if (res.data.sysCode === 1) {
                    let arr = res.data.data

                    if (arr.length) {
                        let gallery = this.data.gallery || []
                        let _gallery = this.data._gallery || []
                        gallery[idx] = {}
                        _gallery[idx] = {}

                        _gallery[idx].galleryItems = arr.slice(0, 2)
                        _gallery[idx].galleryImages = arr.slice(2)

                        // 验证产品名是否过长
                        // let regExp = /\（.+\）$/
                        _gallery[idx].galleryItems.forEach(item => {
                            if ([...item.productName].length > 6) {
                                item.productName = item.productName.slice(0, 6) + '...'
                            }
                        })
                        
                        // 指定最开始加载的页面
                        if (idx === this.data.activeIndex) {
                            gallery[idx] = _gallery[idx]
                        }

                        this.setData({
                            gallery,
                            _gallery
                        });

                        // 需要人工调整，当第四组数据获取成功时，取消下拉刷新动画
                        if (idx === 3) {
                            wx.stopPullDownRefresh();                          
                        }
                    }
                }
            }.bind(this)
        })
    },

    setGallery (idx) {
        let gallery = this.data.gallery
        !gallery[idx].galleryItems 
        && (gallery[idx] = this.data._gallery[idx])
        this.setData({
            gallery
        })
    },

    getTabs () {
        let self = this
        wx.request({
            url: HOST + 'v1/dictionary/getListByType/0/productType',
            method: 'GET', 
            success: function(res){
                if (res.data.sysCode === 1) {
                    self.setData({
                        tabs: res.data.data
                    })
                }
            }
        })
    },

    /** 生命周期 **/
    onLoad (options) {
        let that = this;
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    sliderLeft: res.windowWidth / 75 * 2
                });
            }
        });

        this.getBanners();
        this.getGallerys();
        this.getTabs();

        // 记录带参数二维码参数
        let qrcode = {};
        if (options.store) {
            qrcode.key = '50948b19-67b8-42ff-b857-dbd35295b89s';
            qrcode.value = options.store;
        } else if (options.location) {
            qrcode.key = '50948b19-67b8-42ff-b857-dbd35295b83s';
            qrcode.value = options.location;
        } else {
            options.key && (qrcode.key = options.key);
            options.value && (qrcode.value = options.value);
        }

        // 将二维码存放于 App 中
        // app.globalData.qrcode = qrcode;

        // 将二维码存放于 storage 中
        if (qrcode.key && qrcode.value) {
            wx.setStorage({
                key: 'qrcode',
                data: qrcode,
                success () {
                    console.log('更新二维码参数成功！');
                },
                fail () {
                    console.log('更新二维码参数失败！');
                }
            })
        }
    },

    onPullDownRefresh () {
        this.getGallerys();        
    }
})
